# -*- coding: utf-8 -*-
"""
@Time: 2025/1/10 11:41
@Auth: Zhang Hongxing
@File: report_routes.py
@Note:   
"""
from flask import Blueprint, request, jsonify
from functools import wraps
import jwt
from datetime import datetime, timedelta
# 配置信息
SECRET_KEY = 'your_secret_key'
TOKEN_EXPIRATION = 24 * 60 * 60  # 24小时过期


def decode_token(token):
    """
    解码JWT令牌
    """
    try:
        # 明确指定算法和验证选项
        payload = jwt.decode(
            token,
            SECRET_KEY,
            algorithms=['HS256'],
            options={
                'verify_exp': True,  # 验证过期时间
                'verify_iat': True,  # 验证签发时间
            }
        )
        return payload
    except jwt.ExpiredSignatureError:
        print("令牌已过期")
        return None
    except jwt.InvalidTokenError as e:
        print(f"无效的令牌: {str(e)}")
        return None
    except Exception as e:
        print(f"令牌解析错误: {str(e)}")
        return None


def token_required(f):
    """
    Token验证装饰器
    """

    @wraps(f)
    def decorated(*args, **kwargs):
        # 获取Authorization头
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({
                "code": 401,
                "message": "缺少Authorization头信息"
            }), 401

        # 验证Bearer格式
        parts = auth_header.split()
        if parts[0].lower() != 'bearer' or len(parts) != 2:
            return jsonify({
                "code": 401,
                "message": "无效的Authorization格式"
            }), 401

        token = parts[1]
        payload = decode_token(token)

        if payload is None:
            return jsonify({
                "code": 401,
                "message": "无效或过期的令牌"
            }), 401

        try:
            # 验证令牌中的必要信息
            if 'user_id' not in payload:
                return jsonify({
                    "code": 401,
                    "message": "令牌缺少用户信息"
                }), 401

            # 验证令牌是否过期
            exp_timestamp = payload.get('exp')
            if exp_timestamp is None:
                return jsonify({
                    "code": 401,
                    "message": "令牌缺少过期时间"
                }), 401

            current_timestamp = datetime.utcnow().timestamp()
            if current_timestamp > exp_timestamp:
                return jsonify({
                    "code": 401,
                    "message": "令牌已过期"
                }), 401

            # 将用户信息添加到请求上下文
            return f(payload['user_id'], *args, **kwargs)

        except Exception as e:
            return jsonify({
                "code": 401,
                "message": f"令牌验证失败: {str(e)}"
            }), 401

    return decorated